package cc.telecomdigital.tdstock.adapter;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.List;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import cc.telecomdigital.tdstock.CommonDefn;
import cc.telecomdigital.tdstock.DBHelper;
import cc.telecomdigital.tdstock.DateUtils;
import cc.telecomdigital.tdstock.DefaultClickHandler;
import cc.telecomdigital.tdstock.ITDLApplication;
import cc.telecomdigital.tdstock.R;
import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;
import cc.telecomdigital.tdstock.activity.groups.monitor.StockDiaryActivity;
import cc.telecomdigital.tdstock.activity.groups.monitor.StockDiaryEditActivity;

public class UserDiaryItemAdapter extends BaseAdapter
{
	private LayoutInflater		minflater;
	private List<UserDiaryHolder>	list;
	private static NumberFormat	_formaterOnSacle	= DecimalFormat.getInstance();
	private DBHelper			_dbHelper;
    private static final String TAG=UserDiaryItemAdapter.class.getSimpleName();

	public UserDiaryItemAdapter(LayoutInflater inflater,
			List<UserDiaryHolder> list)
	{
		super();
		this.minflater = inflater;
		this.list = list;
		if(_dbHelper==null){
			_dbHelper=new DBHelper(minflater.getContext());
		}
		_formaterOnSacle.setMaximumFractionDigits(4);
		_formaterOnSacle.setMinimumFractionDigits(0);
	}

	@Override
	public int getCount()
	{
		// TODO Auto-generated method stub
		return this.list.size();
	}

	@Override
	public Object getItem(int position)
	{
		return position < this.list.size() ? this.list.get(position) : null;
	}

	@Override
	public long getItemId(int position)
	{
		return position < this.list.size() ? this.list.get(position).id : -1l;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent)
	{
		UserDiaryHolder commHolder = null;
		if (convertView == null)
		{
			//convertView = minflater.inflate(R.layout.moreitem, null);
			convertView = minflater.inflate(R.layout.user_diary_item, null);
			commHolder = new UserDiaryHolder();
			commHolder.header = (TextView) convertView
					.findViewById(R.id.diary_header);
			commHolder.net = (TextView) convertView
					.findViewById(R.id.diary_net);
			commHolder.desc = (TextView) convertView
					.findViewById(R.id.diary_desc);
			convertView.setTag(commHolder);
		}
		else
		{
			commHolder = (UserDiaryHolder) convertView.getTag();
		}

		commHolder.id = this.list.get(position).id;
		commHolder.itemCode = this.list.get(position).itemCode;
		commHolder.diaryPrice = this.list.get(position).diaryPrice;
		commHolder.lotsize = this.list.get(position).lotsize;
		commHolder.date = this.list.get(position).date;
		commHolder.currentPrice = this.list.get(position).currentPrice;

		commHolder.header.setText(String.format("%s  %d@ $ %s", DateUtils.formatDate(commHolder.date, "yyyy年MM月dd日"),
		commHolder.lotsize, String.valueOf(commHolder.diaryPrice)));

		if (!TextUtils.isDigitsOnly(commHolder.itemCode))
		{
			//  commHolder.net.setText(   (commHolder.currentPrice >=  commHolder.diaryPrice ? "+$" : "-$") +  _formaterOnSacle.format(Math.abs(commHolder.currentPrice - commHolder.diaryPrice)));
			commHolder.net.setText((commHolder.currentPrice >= commHolder.diaryPrice ? "+$"
							: "-$")
							+ _formaterOnSacle
									.format(Math.abs(commHolder.currentPrice- commHolder.diaryPrice)));
		}
		else
		{
			commHolder.net
					.setText((commHolder.currentPrice >= commHolder.diaryPrice ? "+$"
							: "-$")
							+ _formaterOnSacle
									.format(commHolder.lotsize
											* Math.abs(commHolder.currentPrice- commHolder.diaryPrice)));
		}

		commHolder.net.setTextColor(commHolder.currentPrice >= commHolder.diaryPrice ? Color.GREEN: Color.RED);
		//Toast.makeText(context, this.list.get(1).desc.getText(), Toast.LENGTH_SHORT).show();
		//String s=this.list.get(position).desc.getText().toString();
		commHolder.desc.setText(this.list.get(position).desc.getText());
		
		/**+++++++++++++++++++++++++Author: hunter    Time:2011-9.26++++++++++++++++++**/
		parent.setBackgroundResource(R.drawable.four_white_corner_listview_bg);
		
		Button edit = (Button)convertView.findViewById(R.id.diary_edit);
		edit.setOnClickListener(new EdtDiary(minflater.getContext(), position));
		
		Button delete =(Button)convertView.findViewById(R.id.diary_delete);
		delete.setOnClickListener(new DelDiary(minflater.getContext(), position));
		
		//((RelativeLayout)convertView).setOnClickListener(new EdtDiary(minflater.getContext(), position));
		
		/**Author: hunter    Time:2011-9.26**/
		/*Test: return null  */
		//return null;
		return convertView;
	}
	
	
	/**
	 * this is edit diary class
	 * @author hunter
	 *
	 */
	 public class EdtDiary extends DefaultClickHandler
	{
		int	_position;
        
		public EdtDiary(Context context, int pos)
		{
			super(context);
			_position = pos;
		}

		@Override
		protected void onDefaultAction()
		{
			Context context=minflater.getContext();
			StockDiaryActivity   stockdiaryactivity;
			if(context instanceof StockDiaryActivity){
				stockdiaryactivity=(StockDiaryActivity)context;
			}else{
				TDStockLog.d(TAG, "context  is not stockdiaryactivity  class instance");
				return;
			}
			ITDLApplication app = (ITDLApplication) minflater.getContext().getApplicationContext();
			app.putString(CommonDefn.STOCK_DIARY_EDITING_CURRENT_RECNO,
					String.valueOf(stockdiaryactivity.get_list().get(_position).id));

			app.putString(CommonDefn.STOCK_DIARY_EDITING_DATE, DateUtils
					.formatDate(stockdiaryactivity.get_list().get(_position).date, "yyyy-MM-dd"));
			app.putString(CommonDefn.STOCK_DIARY_EDITING_OFSHARES, String
					.valueOf(stockdiaryactivity.get_list().get(_position).lotsize));
			app.putString(CommonDefn.STOCK_DIARY_EDITING_DIARY_PRICE, String
					.valueOf(stockdiaryactivity.get_list().get(_position).diaryPrice));

			app.putString(CommonDefn.STOCK_DIARY_EDITING_MEMO,stockdiaryactivity.get_list().get(_position).desc.getText().toString());

			/*Intent intent =new Intent(getApplicationContext(),StockDiaryEditActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
			startActivity(intent);*/

			Intent intent = new Intent(minflater.getContext().getApplicationContext(),
					StockDiaryEditActivity.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_NO_USER_ACTION);
		/*	View view = MonitorGroup.group.getLocalActivityManager()
					.startActivity(
							StockDiaryEditActivity.class.getSimpleName()
									+ CommonDefn.ANOTHER_INSTANCE,
							intent).getDecorView();
			MonitorGroup.group.setContentView(view); //modified by haibo, 2011-05-16
*/
			stockdiaryactivity.SwitchForwardActivity(intent);
			
		}

	}
	
	 /**
	  * this is delete diary class
	  * @author hunter
	  *
	  */
	 class DelDiary extends DefaultClickHandler
		{
			int	_position;

			public DelDiary(Context context ,int pos)
			{
				super(context);
				_position = pos;
			}

			@Override
			protected void onDefaultAction()
			{
				Context context=minflater.getContext();
				final StockDiaryActivity   stockdiaryactivity;
				if(context instanceof StockDiaryActivity){
					stockdiaryactivity=(StockDiaryActivity)context;
				}else{
					TDStockLog.d(TAG, "context  is not stockdiaryactivity  class instance");
					return;
				}
				new AlertDialog.Builder(stockdiaryactivity.getParent())
						.setTitle(minflater.getContext().getResources().getString(R.string.info))
						.setMessage("確定刪除該記錄？")
						.setIcon(minflater.getContext().getResources().getDrawable(R.drawable.help_menu_icon))
						.setPositiveButton(minflater.getContext().getResources().getString(R.string.ok),
								new DialogInterface.OnClickListener()
								{
									public void onClick(
											DialogInterface dialoginterface,
											int i)
									{
										_dbHelper.deleteStockDiary((int) (stockdiaryactivity.get_list()
														.get(_position).id));
										stockdiaryactivity.get_list().remove(_position);
										UserDiaryItemAdapter.this.notifyDataSetChanged();
									}
								}).setNegativeButton(
									((StockDiaryActivity)minflater.getContext()).getResources().getString(R.string.cancel),new DialogInterface.OnClickListener()
								{
									public void onClick(
											DialogInterface dialog,
											int whichButton)
									{

									}
								}).show();

			}

		}

}
